package com.example.PolimiAssistant;


import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.PagerTitleStrip;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.util.TypedValue;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;
import com.Wsdl2Code.WebServices.PolimiAssistant.UserCurrentSchedule;
import com.Wsdl2Code.WebServices.PolimiAssistant.UserProfile;
import com.example.PolimiAssistant.adapters.AcademicSchedulePageAdapter;
import com.example.PolimiAssistant.common.DialogHandler;
import com.example.PolimiAssistant.utils.AccountDataManager;
import com.example.PolimiAssistant.utils.PreferencesManager;
import com.example.PolimiAssistant.utils.UserDataManager;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * AcademicSchedule.java
 *
 * This activity display the academic schedule to the user.
 *
 */
public class AcademicSchedule extends FragmentActivity {

    /**
     * Declare the context of the application
     */
    protected Context context = this;

    /**
     * The tag used for the logs.
     */
    protected final String TAG = context.getClass().getSimpleName();

    /**
     * The page adapter use to dynamically call the pages for the viewPager
     */
    private AcademicSchedulePageAdapter academicSchedulePageAdapter;

    /**
     * The view pager class used for the swipe pages functionality
     */
    private ViewPager viewPager;

    /**
     *  The processed schedule that was obtained from the server, saved in memory.
     */
    private Map<String, ArrayList<UserCurrentSchedule>> scheduleList;

    public void onCreate(Bundle savedInstanceState) {

        //Activity initialization
        super.onCreate(savedInstanceState);
        setContentView(R.layout.academic_schedule_screen);

        //Update the information on the views
        new UpdateData().execute();

        //Styling the pager tab strip
        PagerTitleStrip pagerTitleStrip = (PagerTitleStrip)findViewById(
                R.id.academic_schedule_pager_title_strip);
        pagerTitleStrip.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 30);
        pagerTitleStrip.setTextSpacing(80);


    }

    public void updateViews() {

        Log.i(TAG, "Updating the basic user information...");

        //View pager initialization
        academicSchedulePageAdapter = new AcademicSchedulePageAdapter(context,
                getSupportFragmentManager(), scheduleList);

        viewPager = (ViewPager) findViewById(R.id.academic_schedule_layout);
        viewPager.setAdapter(academicSchedulePageAdapter);

    }

    private class UpdateData extends AsyncTask<Void, Void, String>
    {

        //1. Create the loading dialog
        ProgressDialog loadingDialog;
        {
            loadingDialog = new ProgressDialog(AcademicSchedule.this);
        }

        @Override
        protected void onPreExecute() {

            super.onPreExecute();

            //2. Set the message and show the dialog
            loadingDialog.setMessage("Loading...");
            loadingDialog.show();
        }

        @Override
        protected String doInBackground(Void... params) {

            //3. Get the token from the preferences
            PreferencesManager preferencesManager = new PreferencesManager(context);
            String token = preferencesManager.getToken();

            Log.i(TAG, "Retrieved token from the preferences: "+token);

            //4. Check if the token is valid
            String valid;
            UserProfile poliUser;
            poliUser = UserDataManager.getUserProfile(token);

            if(poliUser != null){

                //5. Obtain the user schedule from the data manager
                scheduleList = UserDataManager.getAcademicSchedule(token);

                //If the token is still valid or not, declared it
                if(poliUser.valid){
                    valid = "VALID";
                }else{
                    valid = "NOT_VALID";
                }

                Log.i(TAG, "Retrieved the schedule list from the server");

            }else{
                 valid = "WS_ERROR";
            }

            return valid;
        }

        @Override
        protected void onPostExecute(String valid) {

            super.onPostExecute(valid);

            //6. Check if the token is valid and log out the user accordingly and manage WS errors
            if(valid.contentEquals("WS_ERROR")){

                Toast.makeText(context,
                        "The web service is not available in this moment, try again later",
                        Toast.LENGTH_LONG)
                        .show();


            }else if(valid.contentEquals("VALID")){

                updateViews();

            }else{

                Log.i(TAG, "The token is not valid anymore");
                invalidTokenLogOut();
            }


            //Dismiss the loading dialog
            loadingDialog.dismiss();
        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu items for use in the action bar
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu, menu);

        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle presses on the action bar items
        switch (item.getItemId()) {
            case R.id.action_sync:
                //sync();
                return true;
            case R.id.action_settings:
                openSettings();
                return true;
            case R.id.action_logout:
                logOut();
                return true;
            case R.id.action_about:
                //openAbout();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    /**
     * This method open the settings activity
     */
    private void openSettings(){

        Intent goToSettings;

        goToSettings = new Intent(context, Preferences.class);
        startActivity(goToSettings);
    }

    /**
     * This method retrieves the information from the server and updates
     * all the student data in the phone
     */
    private void sync(){

    }

    /**
     * This method erase all of the user personal information stored in the
     * device and eliminate the user account from the android account
     * manager
     */
    public void logOut() {

        //1. Get the message strings
        String dialogMessage;
        dialogMessage = getResources().getString(R.string.logout_message_body);

        String dialogTitle;
        dialogTitle = getResources().getString(R.string.logout_message_title);

        String dialogYes;
        dialogYes = getResources().getString(R.string.logout_message_yes);

        String dialogNo;
        dialogNo = getResources().getString(R.string.logout_message_no);

        //2. Build and display the dialog
        DialogHandler dialog;
        dialog = new DialogHandler();
        dialog.confirmDialog(this, dialogTitle, dialogMessage, dialogYes, dialogNo,
                confirmlogOut(), denylogOut());



    }

    public Runnable confirmlogOut(){

        return new Runnable(){

            public void run(){

                //1. Get the username from the preferences
                PreferencesManager preferencesManager = new PreferencesManager(context);
                String username = preferencesManager.getUsername();

                //2. Delete the account using the account manager
                AccountDataManager.deleteAccount(context, username);

                //3. Create intent to go to the login screen
                Intent goToLogin;
                goToLogin = new Intent(context, LoginScreen.class);
                startActivity(goToLogin);

                //4. Inform the user
                Toast.makeText(context, "You have been logged out",
                        Toast.LENGTH_LONG).show();

                Log.i(TAG, "Logging out the user");
            }
        };
    }

    public Runnable denylogOut(){

        return new Runnable(){

            public void run(){
                Log.i(TAG,"The user rejected being logged out");
            }
        };
    }

    public void invalidTokenLogOut(){

        //1. Get the username from the preferences
        PreferencesManager preferencesManager = new PreferencesManager(context);
        String username = preferencesManager.getUsername();

        //2. Delete the account using the account manager
        AccountDataManager.deleteAccount(context, username);

        //3. Create intent to go to the login screen
        Intent goToLogin;
        goToLogin = new Intent(context, LoginScreen.class);
        startActivity(goToLogin);

        //4. Inform the user
        Toast.makeText(context, "Your session has expired, you will be logged out",
                Toast.LENGTH_LONG).show();

        Log.i(TAG, "Logging out the user");
    }
}